package com.duomn.mybatis.common.dao.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import com.duomn.mybatis.common.dao.IBaseDao;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public abstract class MybatisBaseDao<M, PK extends Serializable> extends SqlSessionDaoSupport implements IBaseDao<M, PK> {
	
	private static Logger log = LoggerFactory.getLogger(MybatisBaseDao.class);
	
	@Override
	public int countAll() {
		return getSqlSession().selectOne("");
	}
	
	@Override
	public List<M> listAll() {
		// 结果转换
		return getSqlSession().selectList("selct");
	}
	
	public int getInteger(String sql, Object param) {
		log.debug("getInteger:" + sql + "[" 
				+ (param == null ? "" : param.toString()) + "]");
		Number num = getSqlSession().selectOne(sql, param);
		return num.intValue();
	}
	
	public long getLong(String sql, Object param) {
		log.debug("getLong:" + sql + "[" 
				+ (param == null ? "" : param.toString()) + "]");
		Number num = getSqlSession().selectOne(sql, param);
		return num.longValue();
	}
	
	public List<M> queryList(String sql, Object	param) {
		log.debug("queryList:" + sql + "[" 
				+ (param == null ? "" : param.toString()) + "]");
		return getSqlSession().selectList(sql, param);
	}

	public M queryOne(String sql, Object param) {
		log.debug("queryOne:" + sql + "[" 
				+ (param == null ? "" : param.toString()) + "]");
		return getSqlSession().selectOne(sql, param);
	}
	
	/**
	 * 获取记录集，组成一个map
	 * @param sql 查询的语句
	 * @param param 参数
	 * @param mapKey 用作key值的列名
	 * @return
	 */
	public <K, V> Map<K, V> queryMap(String sql, Object param, String mapKey) {
		log.debug("queryMap:" + sql + "(columeKey:" + mapKey + ")" 
					+ "[" + (param == null ? "" : param.toString()) + "]");
		return getSqlSession().selectMap(sql, param, mapKey);
	}
	
	public int exec(String sql, Object param) {
		String compare = sql.toLowerCase();
		if (compare.indexOf("insert") != -1 || compare.indexOf("add") != -1 
				|| compare.indexOf("create") != -1 || compare.indexOf("save") != -1) {
			log.debug("execInsert:" + sql + "[" 
				+ (param == null ? "" : param.toString()) + "]");
			return getSqlSession().insert(sql, param);
		} else if (compare.indexOf("update") != -1
				|| compare.indexOf("edit") != -1
				|| compare.indexOf("modify") != -1) {
			log.debug("execUpdate:" + sql + "[" 
					+ (param == null ? "" : param.toString()) + "]");
			return getSqlSession().update(sql, param);
		} else {
			log.debug("execDelete:" + sql + "[" 
					+ (param == null ? "" : param.toString()) + "]");
			return getSqlSession().delete(sql, param);
		}
		
	}

}
